<template>
  <div class="banner-add page-container">
    <div class="page-header">
      <div class="header-left">
        <el-button link @click="goBack" class="back-btn">
          <svg class="back-icon" viewBox="0 0 24 24" fill="currentColor">
            <path
              d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"
            />
          </svg>
          返回
        </el-button>
      </div>
      <div class="header-content">
        <h1 class="page-title">新建Banner</h1>
        <p class="page-subtitle">创建新的Banner，支持图片裁剪和预览功能</p>
      </div>
    </div>

    <div class="content-card" v-loading="loading">
      <el-form
        :model="bannerForm"
        :rules="bannerRules"
        label-width="120px"
        class="banner-form"
        ref="formRef"
      >
        <div class="form-section">
          <div class="section-header">
            <div class="section-icon">
              <svg viewBox="0 0 24 24" fill="currentColor">
                <path
                  d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"
                />
              </svg>
            </div>
            <h3 class="section-title">基本信息</h3>
          </div>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="Banner名称" prop="bannerName">
                <el-input
                  v-model="bannerForm.bannerName"
                  placeholder="请输入Banner名称"
                  maxlength="50"
                  show-word-limit
                  class="custom-input"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-radio-group
                  v-model="bannerForm.status"
                  class="custom-radio-group"
                >
                  <el-radio :label="1" class="custom-radio">
                    <span class="radio-label">显示</span>
                  </el-radio>
                  <el-radio :label="0" class="custom-radio">
                    <span class="radio-label">隐藏</span>
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="关联商品" prop="spuId">
                <el-select
                  v-model="bannerForm.spuId"
                  filterable
                  remote
                  clearable
                  reserve-keyword
                  placeholder="输入商品名称搜索并选择"
                  :remote-method="searchProducts"
                  :loading="productLoading"
                  class="custom-select"
                >
                  <el-option
                    v-for="item in productOptions"
                    :key="item.id"
                    :label="item.spuName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="form-section">
          <div class="section-header">
            <div class="section-icon">
              <svg viewBox="0 0 24 24" fill="currentColor">
                <path
                  d="M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z"
                />
              </svg>
            </div>
            <h3 class="section-title">Banner图片</h3>
            <div class="section-badge">750×250</div>
          </div>

          <div class="image-upload-container">
            <ImageCropperUpload
              :width="750"
              :height="250"
              :fixed-number="[3, 1]"
              @imgupload="handleImageUploadSuccess"
            />
          </div>
        </div>
      </el-form>

      <div class="footer-content">
        <el-button @click="goBack" size="large" class="cancel-btn"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click="handleSubmit"
          :loading="submitting"
          size="large"
          class="submit-btn"
        >
          <svg class="btn-icon" viewBox="0 0 24 24" fill="currentColor">
            <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z" />
          </svg>
          保存Banner
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { postWithAuth } from "@/utils/request";
import ImageCropperUpload from "@/components/ImageCropperUpload.vue";

const router = useRouter();
const formRef = ref();
const loading = ref(false);
const submitting = ref(false);

// 商品选项类型
interface ProductOption {
  id: string | number;
  spuName: string;
}

// 远程商品搜索状态
const productOptions = ref<ProductOption[]>([]);
const productLoading = ref(false);

const bannerForm = reactive({
  bannerName: "",
  bannerImage: "",
  status: 1,
  spuId: null as string | number | null,
});

const bannerRules = {
  bannerName: [
    { required: true, message: "请输入Banner名称", trigger: "blur" },
  ],
  bannerImage: [
    { required: true, message: "请上传Banner图片", trigger: "change" },
  ],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
};

const goBack = () => {
  router.push("/banners");
};

// 远程搜索商品（根据名称匹配）
const searchProducts = async (keyword: string) => {
  try {
    productLoading.value = true;
    const response = await postWithAuth("/internal/product/pageList", {
      spuName: keyword || "",
      status: 1,
      pageIndex: 1,
      pageSize: 20,
    });

    if (response.code === 0) {
      const list = response.data?.list || [];
      productOptions.value = list.map((item: any) => ({
        id: item.id,
        spuName: item.spuName,
      }));
    } else {
      ElMessage.error(response.message || "获取商品列表失败");
    }
  } catch (error) {
    console.error("获取商品列表失败:", error);
    ElMessage.error("获取商品列表失败");
  } finally {
    productLoading.value = false;
  }
};

// 初始加载一次，便于直接下拉选择
onMounted(() => {
  searchProducts("");
});

// 图片上传相关函数
const handleImageUploadSuccess = (imageUrl: string | null) => {
  console.log("图片上传回调:", imageUrl);
  if (imageUrl) {
    bannerForm.bannerImage = imageUrl;
    ElMessage.success("图片上传成功");
    console.log("表单图片地址已更新:", bannerForm.bannerImage);
  } else {
    bannerForm.bannerImage = "";
    console.log("图片已删除，表单图片地址已清空");
  }
};

const handleSubmit = async () => {
  try {
    // 表单验证
    await formRef.value?.validate();

    console.log("提交时的表单数据:", bannerForm);
    console.log("图片地址:", bannerForm.bannerImage);

    if (!bannerForm.bannerImage || !bannerForm.bannerImage.trim()) {
      ElMessage.error("请上传Banner图片");
      return;
    }

    submitting.value = true;

    const response = await postWithAuth("/internal/banners/create", bannerForm);
    if (response.code === 0) {
      ElMessage.success("Banner创建成功");
      router.push("/banners");
    } else {
      ElMessage.error(response.message || "创建失败");
    }
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("提交失败");
  } finally {
    submitting.value = false;
  }
};
</script>

<style scoped>
.banner-add {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.header-left {
  margin-right: 20px;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
  font-size: 14px;
}

.back-icon {
  width: 16px;
  height: 16px;
}

.header-content {
  flex: 1;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-subtitle {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.content-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  padding-bottom: 80px;
}

.banner-form {
  padding: 20px 0;
}

/* 表单区域样式 */
.form-section {
  margin-bottom: 30px;
  padding: 24px;
  border: 1px solid #e4e7ed;
  border-radius: 12px;
  background-color: #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
}

.form-section:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  border-color: #c0c4cc;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebeef5;
}

.section-icon {
  margin-right: 12px;
  color: #409eff;
}

.section-icon svg {
  width: 24px;
  height: 24px;
}

.section-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.section-badge {
  margin-left: 12px;
  font-size: 12px;
  color: #67c23a;
  background-color: #f0f9ff;
  border: 1px solid #d9ecff;
  border-radius: 6px;
  padding: 4px 8px;
  font-weight: 500;
}

/* 自定义输入框样式 */
.custom-input .el-input__inner {
  border-radius: 8px;
  border: 1px solid #dcdfe6;
  padding: 10px 14px;
  font-size: 14px;
  color: #303133;
  transition: all 0.3s ease;
}

.custom-input .el-input__inner:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
}

.custom-input .el-input__inner:hover {
  border-color: #c0c4cc;
}

/* 自定义单选框样式 */
.custom-radio-group .el-radio {
  margin-right: 24px;
}

.custom-radio .el-radio__label {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.custom-radio .el-radio__input.is-checked .el-radio__inner {
  background-color: #409eff;
  border-color: #409eff;
}

.custom-radio .el-radio__input.is-checked .el-radio__inner:after {
  background-color: #fff;
}

/* 自定义选择框样式 */
.custom-select .el-input__inner {
  border-radius: 8px;
  border: 1px solid #dcdfe6;
  padding: 10px 14px;
  font-size: 14px;
  color: #303133;
  transition: all 0.3s ease;
}

.custom-select .el-input__inner:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
}

.custom-select .el-input__inner:hover {
  border-color: #c0c4cc;
}

/* 图片上传样式 */
.image-upload-container {
  width: 100%;
  padding: 20px;
  border-radius: 12px;
  transition: all 0.3s ease;
}

.image-upload-container:hover {
  border-color: #409eff;
  background: linear-gradient(135deg, #f0f9ff 0%, #e1f3ff 100%);
}

/* 预览区域样式 */
.preview-area {
  margin-top: 20px;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.preview-header h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.preview-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 4px;
}

.btn-icon {
  width: 18px;
  height: 18px;
  margin-right: 8px;
}

.preview-image {
  width: 100%;
  max-width: 800px;
  height: 167px;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
  object-fit: cover;
}

/* 底部按钮区域 */
.footer-content {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-top: 1px solid #e4e7ed;
  padding: 20px 24px;
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  z-index: 1000;
  box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.08);
}

.cancel-btn {
  background-color: #f5f7fa;
  border-color: #dcdfe6;
  color: #606266;
  border-radius: 8px;
  padding: 12px 24px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  background-color: #e4e7ed;
  border-color: #c0c4cc;
  color: #303133;
}

.submit-btn {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  border-color: #409eff;
  color: white;
  border-radius: 8px;
  padding: 12px 24px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.submit-btn:hover {
  background: linear-gradient(135deg, #66b1ff 0%, #85c1ff 100%);
  border-color: #66b1ff;
  box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4);
  transform: translateY(-1px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .footer-content {
    flex-direction: column;
  }
}
</style>
